<?php
include_once("config.php");

// Check user not logged in already:
checkLoggedIn("no");

/*
 Accepting a <form> submission:
 The $submit variable in the $_POST superglobal array will only be set if the user has clicked on the 'submit'
 button.  This is a reasonable way to check that the user did in fact submit the form.
 */
if($_POST["submit"]){
	// Info has been submitted, check it:
	// Check login, password and password2 are not empty:
	# field_validator($field_descr, $field_data, $field_type, $min_length="", $max_length="", $field_required=1) {
	field_validator("Логин", $_POST["login"], "alphanumeric", 4, 15);
	field_validator("Пароль", $_POST["password"], "string", 4, 15);
	field_validator("Подтверждите пароль", $_POST["password2"], "string", 4, 15);
	field_validator("E-mail", $_POST["email"], "email", 6, 30);
	field_validator("ICQ", $_POST["icq"], "number", 5, 9, 0);
	field_validator("Моб. телефон", $_POST["mobile"], "mobile", 7, 15, 0);
	field_validator("Skype", $_POST["skype"], "alphanumeric", 4, 20, 0);
	field_validator("ID vkontakte", $_POST["vk"], "number", 2, 8, 0);

	// Check that password and password2 match:
	if(strcmp($_POST["password"], $_POST["password2"])) {
		// The password and confirmation password didn't match,
		// Add a message to be displayed to the user:
		$messages[]="Введенные пароли не совпадают";
	}

	/*
	 Checking the login name doesn't already exist in the 'users' table:

	 The idea here is that if an entry already exists
	 in the 'users' db table where 'login' equals $login
	 (ie the login name the user has just provided in the
	 join form), then we return an error message saying that
	 that username is already taken and ask the user to
	 choose another name.
	 */

	// build query:
	$query="SELECT login FROM users WHERE login='".$_POST["login"]."'";

	// Run query:
	$result=mysql_query($query, $link) or die("Ошибка MySQL запроса ($query): ".mysql_error());

	// If a row exists with that username, issue an error message:
	if( ($row=mysql_fetch_array($result)) ){
		$messages[]="Никнейм \"".$_POST["login"]."\" уже занят. Выберите другой.";
	}

	/*
	 Creating a new user entry in the users table:

	 If we got here and no error messages were placed in the $messages array above,
	 then the $user_name that the user provided was valid and we can
	 continue to create an entry in the users table in the mysql db.
	 We also effectively 'login' the user and then forward them to the members.php
	 page using the 'header()' function.
	 */
	if(empty($messages)) {
		// registration ok, get user id and update db with new info:

		//Преобразование даты рождения в формат ггггммдд
		if ($_POST["yborn"]>=1950&&$_POST["yborn"]<=2000&&$_POST["mborn"]>=1
		&&$_POST["mborn"]<=12&&$_POST["dborn"]>=1&&$_POST["dborn"]<=31)
		$born = $_POST["yborn"]*10000 + $_POST["mborn"]*100 + $_POST["dborn"];

		if ($_FILES["photo"]["name"] != '')
		{
			$dir = "photos//";
			$name_of_file = $_FILES["photo"]["name"];
			$_FILES["photo"]["name"] = rand(0, 100000);
			$_FILES["photo"]["name"] .= "_".$name_of_file;
			copy($_FILES["photo"]["tmp_name"], "photos//".$_FILES["photo"]["name"]);
			$photo = $_FILES["photo"]["name"];
		}

		newUser($_POST["login"],
		$_POST["password"],
		$_POST["email"],
		$_POST["icq"],
		$_POST["mobile"],
		$_POST["skype"],
		$_POST["vk"],
		$_POST["name"],
		$_POST["sex"],
		$born,
		$_POST["team"],
		$_POST["smoke"],
		$photo
		);

		// Log the user in:
		cleanMemberSession($_POST["login"], $_POST["password"]);

		// and then redirect them to the members page:
		header("Location: profile.php?".session_name()."=".session_id());

		/*
		 Note this script stops executing after the header() function above!
		 (the user is forwarded to the members.php page)
		 */
	}
}
/*
 Below here is HTML interposed with PHP.  This HTML is only output if
 a. the form hasn't been submitted
 b. the form was submitted but errors were detected
 */
?>
<html>
<head>
<title><?php print $title ?></title>
<?php doCSS()?>
</head>
<body>
<form action="<?=$_SERVER["PHP_SELF"]?>" method="POST"
	enctype="multipart/form-data">
<table width=450>
	<tr><td colspan=2>
		<?php
			//Check if $message is set, and output it if it is:
			if(!empty($messages)){
				displayErrors("form", $messages);
			}
		?>
	</td></tr>
	<tr>
		<td colspan=2 class=up>Обязательная информация</td>
	</tr  class=n>
	<tr class=n>
		<td width=150>Логин</td>
		<td><input type="text" name="login"
			value="<?php print $_POST["login"] ?>" maxlength="20">*</td>
	</tr>
	<tr class=n>
		<td>Пароль</td>
		<td><input type="password" name="password" value="" maxlength="20">*</td>
	</tr>
	<tr class=n>
		<td>Подтвердите пароль</td>
		<td><input type="password" name="password2" value="" maxlength="20">*</td>
	</tr>
	<tr class=n>
		<td>E-mail</td>
		<td><input type="text" name="email"
			value="<?php print $_POST["email"] ?>" maxlength="30">*</td>
	</tr>

	<tr>
		<td colspan=2 class=up>Контактная информация</td>
	</tr>
	<tr class=n>
		<td>ICQ</td>
		<td><input type="text" name="icq" value="<?php print $_POST["icq"] ?>"
			maxlength="9"></td>
	</tr>
	<tr class=n>
		<td>Моб. телефон</td>
		<td><input type="text" name="mobile"
			value="<?php print $_POST["mobile"] ?>" maxlength="15"></td>
	</tr>
	<tr class=n>
		<td>Skype</td>
		<td><input type="text" name="skype"
			value="<?php print $_POST["skype"] ?>" maxlength="20"></td>
				</tr>
	<tr class=n>
		<td>ID vkontakte</td>
		<td><input type="text" name="vk" value="<?php print $_POST["vk"] ?>"
			maxlength="20"></td>
	</tr>

	<tr>
		<td colspan=2 class=up>Дополнительная информация</td>
	</tr>
	<tr class=n>
		<td>Имя</td>
		<td><input type="text" name="name"
			value="<?php print $_POST["name"] ?>" maxlength="20"></td>
	</tr>
	<tr class=n>
		<td>Пол</td>
		<td><input type="radio" name="sex" value="m">Мужской<br>
		<input type="radio" name="sex" value="w">Женский</td>
	</tr>
	<tr class=n>
		<td>Дата рождения</td>
		<td><input type="text" name="dborn" size="1" maxlength="2" value="дд">
		/ <input type="text" name="mborn" size="1" maxlength="2" value="мм"> /
		<input type="text" name="yborn" size="2" maxlength="4" value="гггг"></td>
	</tr>
	<tr class=n>
		<td>Группа</td>
		<td><input type="radio" name="team" value="1">Пассажир<br>
		<input type="radio" name="team" value="2">Водитель<br>
		<input type="radio" name="team" value="3">Совместно</td>
	</tr>
	<tr class=n>
		<td>Курю</td>
		<td><input type="radio" name="smoke" value="y">Да<br>
		<input type="radio" name="smoke" value="n">Нет</td>
	</tr>
	<tr class=n>
		<td>Фото</td>
		<td><input type="file" name="photo"></td>
	</tr>
	<tr>
		<td colspan=2 class=bot>
		<center><input name="submit" type="submit"
			value="Завершить регистрацию"></center>
		</td>
	</tr>
</table>
</form>
</body>
</html>
